import axios from 'axios'
import router from '../router'
import qs from 'qs'
// import store from '@/store'
import { setToken, getToken } from '@/libs/util'

const addErrorLog = errorInfo => {
    const { statusText, status, request: { responseURL } } = errorInfo
    let info = {
        type: 'ajax',
        code: status,
        mes: statusText,
        url: responseURL
    }
    // if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {

    constructor(baseUrl = baseURL) {
        this.baseUrl = baseUrl
        this.queue = {}
    }

    getInsideConfig() {
        var z = localStorage.getItem('lang')||'zh';
        let locale = z;
        if (z == 'zh') {
            locale = 'zh-CN'
        } else if (z == 'tw') {
            locale = 'zh-HT'
        } else {
            locale = z
        }
        const config = {
            baseURL: this.baseUrl,
            headers: {
                "Authorization": "Bearer " + getToken("token"),
                "from": "pc",
                'lang': locale
            }
        };
        return config
    }

    destroy(url) {
        delete this.queue[url]
        if (!Object.keys(this.queue).length) {
            // Spin.hide()
        }
    }

    interceptors(instance, url) {
        // 请求拦截
        instance.interceptors.request.use(config => {
            // 添加全局的loading...
            if (!Object.keys(this.queue).length) {
                // Spin.show() // 不建议开启，因为界面不友好
            };
            try {
                // if (config.fromdata) { 
                  // 转formdata格式 保持开启
                    config.data = qs.stringify(config.data);
                // };
            }
            catch (err) {

            }
            if (config.method === 'post') {
                for (var key in config.data) {
                    if (config.data[key] === '') {
                        delete config.data[key]
                    };
                };
            };
            this.queue[url] = true;
            return config;
        }, error => {
            return Promise.reject(error)
        })
        // 响应拦截
        instance.interceptors.response.use(res => {
            this.destroy(url);
            if (res.headers.authorization) {
                // setToken(res.headers.authorization)
            };
            if (res.data.status_code == 401) {
                 
                localStorage.removeItem('token');
                router.replace('/login')
                // location.reload();
                return false;
            }
            const { data, status, headers } = res
            return { data, status, headers }
        }, error => {
            this.destroy(url)
            let errorInfo = error.response
            if (!errorInfo) {
                const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
                errorInfo = {
                    statusText,
                    status,
                    request: { responseURL: config.url }
                }
            }
            addErrorLog(errorInfo)
            return Promise.reject(error)
        })
    }
    
    request(options) {
         
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

export default HttpRequest
